<?php

namespace app\common\service\ai;

use think\facade\Db;
use app\common\service\CommonService;

/**
 * 智能文案
 */
class ErnieService extends CommonService {

	/**
	 * API_KEY
	 * @static string
	 */
	const API_KEY = "x81v2MGQ8RfXMzssn2oj02lg";

	/**
	 * SECRET_KEY
	 * @static string
	 */
	const SECRET_KEY = "rfgFKQdVsJQqNHOmBFuh1mlkBrT6lPVL";

	/**
	 * 执行对话
	 * @param array $data
	 * @return array
	 */
	public static function run($data) {
		$curl = curl_init();
		curl_setopt_array($curl, array(
//			CURLOPT_URL => "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token={$this->getAccessToken()}",
			CURLOPT_URL => "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" . self::getAccessToken(),
			CURLOPT_TIMEOUT => 120,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_SSL_VERIFYHOST => false,
			CURLOPT_CUSTOMREQUEST => 'POST',
//			CURLOPT_POSTFIELDS => '{"messages":[{"role":"user","content":"我们"}],"temperature":0.95,"top_p":0.8,"penalty_score":1,"enable_system_memory":false,"disable_search":false,"enable_citation":false}',
			CURLOPT_POSTFIELDS => json_encode($data['post_fields']),
			CURLOPT_HTTPHEADER => array(
				'Content-Type: application/json'
			),
		));
		$response = curl_exec($curl);
		curl_close($curl);
		return $response;
	}

	/**
	 * 使用 AK，SK 生成鉴权签名（Access Token）
	 * @return string 鉴权签名信息（Access Token）
	 */
	private static function getAccessToken() {
		$curl = curl_init();
		$postData = array(
			'grant_type' => 'client_credentials',
			'client_id' => self::API_KEY,
			'client_secret' => self::SECRET_KEY
		);
		curl_setopt_array($curl, array(
			CURLOPT_URL => 'https://aip.baidubce.com/oauth/2.0/token',
			CURLOPT_CUSTOMREQUEST => 'POST',
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_SSL_VERIFYHOST => false,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_POSTFIELDS => http_build_query($postData)
		));
		$response = curl_exec($curl);
		curl_close($curl);
		$rtn = json_decode($response);
		return $rtn->access_token;
	}

	/**
	 * 对话
	 * @param array $data 数据
	 * @return array
	 */
	public static function chat($data) {

        $data['content'] = "以下内容生成适合口播的短视频爆款文案，不要放入表情，字数控制在200以内：".$data['content'];

		$data['post_fields'] = [
			'messages' => [
					[
					'role' => 'user',
					'content' => $data['content'],
				]
			],
			'temperature' => 0.95,
			'top_p' => 0.8,
			'penalty_score' => 1,
			'enable_system_memory' => false,
			'disable_search' => false,
			'enable_citation' => false,
		];
		$res = self::run($data);
		return json_decode($res);
	}

}
